package uk.co.richardwkirk.parkrun.web.parsers;

import org.jsoup.nodes.Comment;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import uk.co.richardwkirk.parkrun.data.athletes.AthleteSummary;


public class AtheleteSummaryResultsParser extends ParkrunWebPageParser {

	public AtheleteSummaryResultsParser(String summaryPageContent) throws ParkrunDataParseException {
		super(summaryPageContent);
	}

	public String getName() {
		// Create a filter to extract the table node we are interested in
		Element h2Node = getFirstMatchingNode("h2");
		
		// Get the name from the filter
		String name = AthleteSummary.UNKNOWN_ATHLETE;
		if (h2Node != null) {
			String titleString = h2Node.text();
			if (!titleString.startsWith("(")) 
			{
				name = titleString.substring(0, titleString.indexOf("(") - 1);
			}
		}
		return name;
	}

	public String getClub() {
		// Get the club number from the link image
		Elements imageNodes = getAllMatchingNodes("img");
		
		// Is this the link we want
		String club = null;
		for (Element imgNode : imageNodes) {
			String clubText = imgNode.attr("alt"); 
			if (clubText != null && clubText.contains("Member of the parkrun")) {
				club = clubText.replace("Member of the parkrun ", "");
				club = club.replace(" club", "");
			}
		}
		return club;
	}

	public String getLoadTime() {
		// Get the time that the page content was generated
		// This is in a comment of the form:
		// <!-- Cached page generated by WP-Super-Cache on 2013-03-10 17:18:29 -->
		String comment = null;
		for (Element e : htmlContent.getAllElements()) {
			for (Node n : e.childNodes()) {
				if (n instanceof Comment) {
					String commentText = ((Comment) n).getData();
					if (commentText != null && commentText.contains("Cached page generated by WP-Super-Cache on")) {
						comment = commentText.replace("Cached page generated by WP-Super-Cache on ", "");
						comment = comment.trim();
						return comment;
					}
				}
			}
		}
		return comment;
	}
	
}
